function N_i=solve_N_i(Nbar_i, A_t, Scost_t, Sunit_t, P_t, PSale_t, PIns0_t, PIns_t, Skwh_t, gamma_N, gamma_2N)

global state_max   statetaxcredit_t statemaxtaxcredit_t sunit_cap_t  net_metering C  over_dist PV_hh PV

nbin=size(Nbar_i,2);
Scost_i=Scost_t*ones(1,nbin);
Sunit_i=Sunit_t*ones(1,nbin);

if state_max==1
    N_mean=15; % mean from deepsolar data
    
    state_sub=statetaxcredit_t.*(PIns0_t+ PIns_t.*N_mean);
    overmax=state_sub>statemaxtaxcredit_t;    
    Scost_i(overmax)=Scost_i(overmax)-statemaxtaxcredit_t(overmax); % if above this cap, then don't receive state credit

    unit_sub=N_mean.*Sunit_i;
    overmax=unit_sub>sunit_cap_t;           % if above this cap, don't receive unit sub

    Sunit_i(overmax)=0;
end




dm_dN= (A_t.*(P_t+Skwh_t) -(1-Scost_i).* PIns_t+Sunit_i);

if over_dist==1
    dm_dN= (A_t.*(P_t+(PV_hh./PV).*Skwh_t) -(1-Scost_i).* PIns_t+Sunit_i);
end


N_i=-(dm_dN+gamma_N)./(2*gamma_2N);

if net_metering==1
    N_i=-(dm_dN+gamma_N)./(2*(gamma_2N- A_t.*C.*(P_t-PSale_t)));
    
end


N_i(N_i<0)=0;
N_i(N_i>Nbar_i)=Nbar_i(N_i>Nbar_i);

